package com.sqnu.dashe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqnu.dashe.common.R;
import com.sqnu.dashe.dto.DishDto;
import com.sqnu.dashe.entity.Category;
import com.sqnu.dashe.entity.Dish;
import com.sqnu.dashe.entity.DishFlavor;
import com.sqnu.dashe.service.CategoryService;
import com.sqnu.dashe.service.DishFlavorService;
import com.sqnu.dashe.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mmy
 * @create 2023-06-10 17:01
 * @description
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavo(dishDto);
        return R.success("添加菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构建分页构造器
        Page<Dish> dishInfo = new Page<>(page, pageSize);
        Page<DishDto> page1 = new Page<>();
        //构建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getCreateTime);

        //进行分页查询
        dishService.page(dishInfo, queryWrapper);
        //对象拷贝,由于dish中没有菜品分类名字参数，而dishDto中存在，故需要dish中的菜品分类id传给page1，
        // 再根据id在DishDto中查找菜品分类名字并返回，故拷贝时把结果集合records忽略
        BeanUtils.copyProperties(dishInfo, page1, "records");
        List<Dish> records = dishInfo.getRecords();
        List<DishDto> list = records.stream().map(item -> {
            //定义一个dishDto对象，用来存储信息并返回
            DishDto dishDto = new DishDto();
            //把遍历出来的每一个dish对象复制给dishDto
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//得到分类id
            Category category = categoryService.getById(categoryId);//得到Category对象
            if (category != null) {
                String name1 = category.getName();
                dishDto.setCategoryName(name1);
            }
            return dishDto;
        }).collect(Collectors.toList());


        page1.setRecords(list);
        //返回结果
        return R.success(page1);
    }

    //删除菜品
    @DeleteMapping()
    public R<String> deleteDishDto(@RequestParam List<Long> ids) {
        log.info("尝试删除菜品:{}", ids);
        dishService.deleteDish(ids);
        return R.success("删除菜品成功");
    }

    //启停售菜品
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("status:{},ids:{}", status, ids);
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(ids != null, Dish::getId, ids);
        updateWrapper.set(Dish::getStatus, status);
        dishService.update(updateWrapper);
        return R.success("批量操作成功");
    }

    @GetMapping("/{id}")
    public R<DishDto> getDishDto(@PathVariable Long id) {
        DishDto byId = dishService.getByIdWithFlavo(id);
        return R.success(byId);
    }

    @PutMapping
    public R<String> saveDish(@RequestBody DishDto dishDto) {
        log.info("修改菜品信息：{}", dishDto);
        dishService.MyUpdateById(dishDto);
        return R.success("菜品信息修改成功");
    }

    /**
     * 查询菜品分类下的菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getCategory(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort);
        //查询状态是启售的商品
        queryWrapper.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map(item -> {
            //定义一个dishDto对象，用来存储信息并返回
            DishDto dishDto = new DishDto();
            //把遍历出来的每一个dish对象复制给dishDto
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//得到分类id
            Category category = categoryService.getById(categoryId);//得到Category对象
            if (category != null) {
                String name1 = category.getName();
                dishDto.setCategoryName(name1);
            }

            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

}
